package org.example.myjavaweb_de.padao;

import org.example.myjavaweb_de.User.Student;
import org.example.myjavaweb_de.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class paqdao {
//单行查询
    public Student queryone(Integer id){
        Connection cn = DbUtil.getConn();
        String sql = "select * from student where id=?";
        try {
            PreparedStatement ps = cn.prepareStatement(sql);
            ps.setInt(1, id);
            ResultSet cs = ps.executeQuery();
            if(cs.next()){
                Student s = new Student(cs.getString("stu"),
                        cs.getString("stus"));
                return s;
            }
        }catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DbUtil.closeConn();
        }
        return null;
    }

//查询所有
    public List<Student>queryall() {
        List<Student> ls = new ArrayList<Student>();
        Connection cn = DbUtil.getConn();
        try {
            String select = "select * from student";
            PreparedStatement preparedStatement = cn.prepareStatement(select);
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                //将查询结果的每行数据 封装为对象 并加入到集合内
                ls.add(new Student(
                                rs.getInt("id"),
                                rs.getString("stu"),
                                rs.getString("stus")
                        )
                );
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DbUtil.closeConn();
        }

        return ls;
    }
}
